package com.smyx.juc;

import java.util.concurrent.CountDownLatch;

/**
 * 利用CountDownLatch统计多个线程的耗时
 * @author SmyxCoding
 * @date 2022-08-11 23:07
 **/
public class CountDownLatchTimeTest {
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 以免程序异常 当前线程得不到释放
                    countDownLatch.countDown();
                }
            }).start();
        }
        // 阻塞下面的代码逻辑
        countDownLatch.await();
        System.out.println("countDownLatch.getCount()>>>> " + countDownLatch.getCount());
        System.out.println("5个线程执行完毕，耗时 >>> " + (System.currentTimeMillis() - start) + "ms");
    }
}
